package com.esen.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.blade.ioc.annotation.Inject;
import com.blade.mvc.annotation.Path;
import com.blade.mvc.annotation.Route;
import com.blade.mvc.http.Request;
import com.blade.mvc.http.Response;
import com.esen.service.UserService;

@Path
public class ActionSQLInjection {

	private static final Logger SLF4J = LoggerFactory.getLogger(ActionSQLInjection.class);

	@Inject
	private UserService userService;

	@Route(value = "/syr/sql/login")
	public void toLoginPage(Response response) {
		response.render("/syr/sql/login.html");
	}

	@Route(value = "/syr/sql/init")
	public void initData(Response response) throws Exception {
		try {
			userService.initData();
			JSONObject obj = new JSONObject();
			obj.put("result", true);
			response.json(obj.toJSONString());
		} catch (Exception e) {
			JSONObject obj = new JSONObject();
			obj.put("result", false);
			response.json(obj.toJSONString());
		}
	}

	@Route(value = "/syr/sql/dologin")
	public void login(Request request, Response response) throws Exception {
		String userid = request.query("id", "");
		String password = request.query("password", "");
		boolean valid = userService.login(userid, password);
		if (valid) {
			JSONObject obj = new JSONObject();
			obj.put("result", true);
			response.json(obj.toJSONString());
		} else {
			JSONObject obj = new JSONObject();
			obj.put("result", false);
			response.json(obj.toJSONString());
		}
	}

	@Route(value = "/syr/sql/update")
	public void update(Request request, Response response) throws Exception {
		String userid = request.query("id", "");
		String password = request.query("password", "");
		try {
			userService.uddatePassword(userid, password);
			JSONObject obj = new JSONObject();
			obj.put("result", true);
			response.json(obj.toJSONString());
		} catch (Exception e) {
			SLF4J.error(e.getMessage(), e);
			JSONObject obj = new JSONObject();
			obj.put("result", false);
			response.json(obj.toJSONString());
		}
	}
}
